global class GenerateUtil{

    static String testVar = '';

    Webservice static String generateContract(String templateId, String requiredDate,String datasource)
    {
        return '';
    }

    Webservice static String generateContract2(String templateId, String requiredDate,String datasource, String attachmentId, String effectiveStartDate, String effectiveEndDate)
    {
        try
        {
            String BATCHID = '';

            String str = 'hello';
            System.LoggingLevel level =
            LoggingLevel.DEBUG;
            String check = 'false';
            Integer totalDataSources = 0;
            Integer planDocsCreated = 0;
            List<Sales_Contract__c> planDocumentsList = new List<Sales_Contract__c>();
            List<BatchDetail__c> batchDetailsList = new List<BatchDetail__c>();

            try
            {
                //Get the Approvers assigned for this Template by Admin before generation of Plan Documents.
                Approvers__c[] approver = [select Admin__c, Template__c, Final_Approver__c, Final_Approver_Date__c, Level1__c, Level2__c, Level3__c, Level4__c, Level5__c, Level6__c, Level7__c, Level8__c, Level9__c, Level10__c, Level11__c, Level12__c, Level13__c, Level14__c, Level15__c, Level1_Due_Date__c, Level2_Due_Date__c, Level3_Due_Date__c, Level4_Due_Date__c, Level5_Due_Date__c, Level6_Due_Date__c, Level7_Due_Date__c, Level8_Due_Date__c, Level9_Due_Date__c, Level10_Due_Date__c, Level11_Due_Date__c, Level12_Due_Date__c, Level13_Due_Date__c, Level14_Due_Date__c, Level15_Due_Date__c from Approvers__c  where Template__c = :templateId and Admin__c = :UserInfo.getUserId() order by CreatedDate desc limit 1];
                
                URL__c[] url = [SELECT Id, Url_Value__c FROM URL__c];

                //Get the AttachmentId of an Attachment associated with the Template.
                Attachment[] templateAttachment = [SELECT Id FROM Attachment a where a.Parent.Id = :templateId];
                if(templateAttachment.size() == 0)
                {
                    return 'No Templates Attached';
                }
                
                //Get the Roles associated with the Template.
                Template_Role__c[] tempRoles = [SELECT Role_ID__c FROM Template_Role__c tempRoles where tempRoles.Template_ID__c= :templateId];
                if(tempRoles.size() == 0)
                {
                    return 'No Roles associated with this Template.';
                }
                Template_Role__c[] tempTitles=[SELECT User_Title__c FROM Template_Role__c tempRoles where tempRoles.Template_ID__c= :templateId];
                if(tempTitles.size() == 0)
                {
                   return ' No Titles Associated with this Template';
                }   
                // Get the titles associated with the Template.
                Template__c[] template = [SELECT Id, Name, EligibilityType__c FROM Template__c tc where tc.Id = :templateId ];
                              
                Batch__c  batch= null;
                BatchDetail__c[] batchdetails=null;
                CallidusDataSource__c[] dsc=null;
                Sales_Contract__c[] contracts= null;

                Date dt = Date.today();
    
                Template__c[] templateName = [SELECT Id, Name  FROM Template__c t where t.Id= :templateId];
                TemplateDataMap__c[]  tempDataMap = [SELECT Id, Name, TemplateName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c,Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c FROM TemplateDataMap__c tmap where tmap.TemplateName__c = :templateName[0].Name];
  
                batch = new Batch__c();
                batch.StartTime__c=datetime.now();
                batch.TotalContracts__c = totalDataSources ;
                batch.RemainingContracts__c = totalDataSources ;
                batch.Status__c='InProgress';
                if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                {
                    batch.Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                }
                
                if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                {
                    batch.Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                }
                
                batch.TemplateId__c= templateId;
                try{
                    insert batch;
                }
                catch(DmlException e)
                {
                    return 'While inserting Batch 1   '+e+'  ';
                }
                
                BATCHID = batch.Id;
                String syncDate = '';
                if(template[0].EligibilityType__c=='Title')
                {
                    if(testVar != '')
                    {
                        tempDataMap[0] = new TemplateDataMap__c();
                        tempDataMap[0].Name1__c = '';
                        tempDataMap[0].Name2__c = '';
                        tempDataMap[0].Name3__c = '';   
                        tempDataMap[0].Name4__c = '';
                        tempDataMap[0].Name5__c = '';
                        tempDataMap[0].Name6__c = '';     
                        tempDataMap[0].Name7__c = '';
                        tempDataMap[0].Name8__c = '';
                        tempDataMap[0].Name9__c = '';   
                        tempDataMap[0].Name10__c = '';
                        tempDataMap[0].Name11__c = '';
                        tempDataMap[0].Name12__c = '';     
                        tempDataMap[0].Name13__c = '';
                        tempDataMap[0].Name14__c = '';
                        tempDataMap[0].Name15__c = '';   
                        tempDataMap[0].Name16__c = '';
                        tempDataMap[0].Name17__c = '';
                        tempDataMap[0].Name18__c = '';     
                        tempDataMap[0].Name19__c = '';
                        tempDataMap[0].Name20__c = '';
                        tempDataMap[0].Name21__c = '';   
                        tempDataMap[0].Name22__c = '';
                        tempDataMap[0].Name23__c = '';
                        tempDataMap[0].Name24__c = '';     
                        tempDataMap[0].Name25__c = '';
                        tempDataMap[0].Name26__c = '';
                        tempDataMap[0].Name27__c = '';   
                        tempDataMap[0].Name28__c = '';
                        tempDataMap[0].Name29__c = '';
                        tempDataMap[0].Name30__c = ''; 
                    }
                    return  defineEligibility2(attachmentId, templateId, requiredDate, datasource, tempTitles, planDocumentsList, tempDataMap, BATCHID, '2008-08-08', '2008-08-09');
                }
                             
                for(Template_Role__c roles:tempRoles)
                {
                    for(CallidusDataSource__c[] src : [SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,UserID__c,UserRoleId__c,UserRoleName__c,User_Title__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserRoleId__c=:roles.Role_ID__c])
                    {
                        contracts = new Sales_Contract__c[src.size()];
                        totalDataSources += src.size();
                        Integer i = 0;
                        for(CallidusDataSource__c sources : src)
                        {
                            syncDate = sources.SyncDate__c;
                            if(sources.PayeeID__c == null && dataSource == 'True Comp')
                            {
                                i++;
                                continue;
                            }
                              
                            check = 'true';  
                
                            contracts[i] = new Sales_Contract__c();
                            contracts[i].FirstName__c=sources.FirstName__c;
                            contracts[i].Generated_Date__c= dt;
                            contracts[i].LastName__c=sources.LastName__c;
                            contracts[i].Status__c= 'Draft';
                            contracts[i].UserID__c= sources.UserID__c;
                            contracts[i].User_ID__c= sources.UserID__c;
                            contracts[i].UserRoleId__c=sources.UserRoleId__c;
                            contracts[i].User_Title__c=sources.User_Title__c;
                            contracts[i].PayeeID__c=sources.PayeeID__c;
                            contracts[i].UserRoleName__c= sources.UserRoleName__c;
                            contracts[i].TemplateName__c=templateName[0].Name;
                            contracts[i].BatchID__c = batch.Id;
                            if(dt.month() > 9)
                                contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+sources.FirstName__c+' '+sources.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                            else
                                contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+sources.FirstName__c+' '+sources.LastName__c+' 0'+dt.month()+'/'+dt.day()+'/'+dt.year();
                            
                            if(approver.size() > 0)
                            {
                                if(testVar != '' && testVar.length() > 0)
                                {
                                    approver[0].Level1__c = '005400000011eqL';
                                    approver[0].Level2__c = '005400000011eqL';
                                    approver[0].Level3__c = '005400000011eqL';
                                    approver[0].Level4__c = '005400000011eqL';
                                    approver[0].Level5__c = '005400000011eqL';
                                    approver[0].Level6__c = '005400000011eqL';
                                    approver[0].Level7__c = '005400000011eqL';
                                    approver[0].Level8__c = '005400000011eqL';
                                    approver[0].Level9__c = '005400000011eqL';
                                    approver[0].Level10__c = '005400000011eqL';
                                    approver[0].Level11__c = '005400000011eqL';
                                    approver[0].Level12__c = '005400000011eqL';
                                    approver[0].Level13__c = '005400000011eqL';
                                    approver[0].Level14__c = '005400000011eqL';
                                    approver[0].Level15__c = '005400000011eqL';
                                    approver[0].Final_Approver__c = '005400000011eqL';
                                    approver[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                                }
                                                
                                contracts[i] = populateSalesContractLevels(contracts[i], approver[0], sources.UserID__c);
                            }
                                
                            if(url.size() > 0)
                            {
                                contracts[i].Url__c = url[0].Url_Value__c;
                            }

                            if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                            {
                                contracts[i].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                            }
                            
                            if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                            {
                                contracts[i].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                            }
                            
                            if(requiredDate.length() > 7 && requiredDate.length() <= 10)
                            {
                                contracts[i].RequiredReturnDate__c = Date.valueOf(requiredDate);
                            }
                            
                            if(datasource!='True Comp')
                            {
                                
                                contracts[i].Name1__c = sources.Name1__c;
                                contracts[i].Name2__c = sources.Name2__c;
                                contracts[i].Name3__c = sources.Name3__c;   
                                contracts[i].Name4__c = sources.Name4__c;
                                contracts[i].Name5__c = sources.Name5__c;
                                contracts[i].Name6__c = sources.Name6__c;     
                                contracts[i].Name7__c = sources.Name7__c;
                                contracts[i].Name8__c = sources.Name8__c;
                                contracts[i].Name9__c = sources.Name9__c;   
                                contracts[i].Name10__c = sources.Name10__c;
                                contracts[i].Name11__c = sources.Name11__c;
                                contracts[i].Name12__c = sources.Name12__c;     
                                contracts[i].Name13__c = sources.Name13__c;
                                contracts[i].Name14__c = sources.Name14__c;
                                contracts[i].Name15__c = sources.Name15__c;   
                                contracts[i].Name16__c = sources.Name16__c;
                                contracts[i].Name17__c = sources.Name17__c;
                                contracts[i].Name18__c = sources.Name18__c;     
                                contracts[i].Name19__c = sources.Name19__c;
                                contracts[i].Name20__c = sources.Name20__c;
                                contracts[i].Name21__c = sources.Name21__c;   
                                contracts[i].Name22__c = sources.Name22__c;
                                contracts[i].Name23__c = sources.Name23__c;
                                contracts[i].Name24__c = sources.Name24__c;     
                                contracts[i].Name25__c = sources.Name25__c;
                                contracts[i].Name26__c = sources.Name26__c;
                                contracts[i].Name27__c = sources.Name27__c;   
                                contracts[i].Name28__c = sources.Name28__c;
                                contracts[i].Name29__c = sources.Name29__c;
                                contracts[i].Name30__c = sources.Name30__c;     
                    
                                contracts[i].Value1__c = sources.Value1__c;
                                contracts[i].Value2__c = sources.Value2__c;
                                contracts[i].Value3__c = sources.Value3__c;
                                contracts[i].Value4__c = sources.Value4__c;
                                contracts[i].Value5__c = sources.Value5__c;
                                contracts[i].Value6__c = sources.Value6__c;
                                contracts[i].Value7__c = sources.Value7__c;
                                contracts[i].Value8__c = sources.Value8__c;
                                contracts[i].Value9__c = sources.Value9__c;
                                contracts[i].Value10__c = sources.Value10__c;
                                contracts[i].Value11__c = sources.Value11__c;
                                contracts[i].Value12__c = sources.Value12__c;
                                contracts[i].Value13__c = sources.Value13__c;
                                contracts[i].Value14__c = sources.Value14__c;
                                contracts[i].Value15__c = sources.Value15__c;
                                contracts[i].Value16__c = sources.Value16__c;
                                contracts[i].Value17__c = sources.Value17__c;
                                contracts[i].Value18__c = sources.Value18__c;
                                contracts[i].Value19__c = sources.Value19__c;
                                contracts[i].Value20__c = sources.Value20__c;
                                contracts[i].Value21__c = sources.Value21__c;
                                contracts[i].Value22__c = sources.Value22__c;
                                contracts[i].Value23__c = sources.Value23__c;
                                contracts[i].Value24__c = sources.Value24__c;
                                contracts[i].Value25__c = sources.Value25__c;
                                contracts[i].Value26__c = sources.Value26__c;
                                contracts[i].Value27__c = sources.Value27__c;
                                contracts[i].Value28__c = sources.Value28__c;
                                contracts[i].Value29__c = sources.Value29__c;
                                contracts[i].Value30__c = sources.Value30__c;
                            }
                            else
                            {
                                if(tempDataMap.size() > 0)
                                {   
                                    
                                    contracts[i].Name1__c = tempDataMap[0].Name1__c;
                                    contracts[i].Name2__c = tempDataMap[0].Name2__c;
                                    contracts[i].Name3__c = tempDataMap[0].Name3__c;   
                                    contracts[i].Name4__c = tempDataMap[0].Name4__c;
                                    contracts[i].Name5__c = tempDataMap[0].Name5__c;
                                    contracts[i].Name6__c = tempDataMap[0].Name6__c;     
                                    contracts[i].Name7__c = tempDataMap[0].Name7__c;
                                    contracts[i].Name8__c = tempDataMap[0].Name8__c;
                                    contracts[i].Name9__c = tempDataMap[0].Name9__c;   
                                    contracts[i].Name10__c = tempDataMap[0].Name10__c;
                                    contracts[i].Name11__c = tempDataMap[0].Name11__c;
                                    contracts[i].Name12__c = tempDataMap[0].Name12__c;     
                                    contracts[i].Name13__c = tempDataMap[0].Name13__c;
                                    contracts[i].Name14__c = tempDataMap[0].Name14__c;
                                    contracts[i].Name15__c = tempDataMap[0].Name15__c;   
                                    contracts[i].Name16__c = tempDataMap[0].Name16__c;
                                    contracts[i].Name17__c = tempDataMap[0].Name17__c;
                                    contracts[i].Name18__c = tempDataMap[0].Name18__c;     
                                    contracts[i].Name19__c = tempDataMap[0].Name19__c;
                                    contracts[i].Name20__c = tempDataMap[0].Name20__c;
                                    contracts[i].Name21__c = tempDataMap[0].Name21__c;   
                                    contracts[i].Name22__c = tempDataMap[0].Name22__c;
                                    contracts[i].Name23__c = tempDataMap[0].Name23__c;
                                    contracts[i].Name24__c = tempDataMap[0].Name24__c;     
                                    contracts[i].Name25__c = tempDataMap[0].Name25__c;
                                    contracts[i].Name26__c = tempDataMap[0].Name26__c;
                                    contracts[i].Name27__c = tempDataMap[0].Name27__c;   
                                    contracts[i].Name28__c = tempDataMap[0].Name28__c;
                                    contracts[i].Name29__c = tempDataMap[0].Name29__c;
                                    contracts[i].Name30__c = tempDataMap[0].Name30__c; 
                                }
                        
                            }
                            
                            contracts[i].AttachmentID__c = templateAttachment[0].Id;
                            planDocumentsList.add(contracts[i]);
                            i++;
                            planDocsCreated++;
                            if(planDocumentsList.size() == 200 || i == src.size())
                            {
                                try
                                {
                                    insert planDocumentsList;
                                }
                                catch(DmlException d)
                                {   
                                    return 'While inserting Contracts   '+d+'   ';
                                }
                                Integer j=0;
                                String ids = '';
                                planDocumentsList.clear();
    
                            }//end of if(planDocumentsList.size() == 199) 
                            
                        }//end of for(CallidusDataSource__c sources : src)

                    }//end of for(CallidusDataSource__c[] sources:[SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,UserID__c,UserRoleId__c,UserRoleName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserRoleId__c=:roles.Role_ID__c])
            
                }//end of for(Template_Role__c roles:tempRoles)
              
                Batch__c[] btch = [SELECT Status__c,TotalContracts__c,RemainingContracts__c, EndTime__c,Datasource__c from Batch__c b where  b.Id = :batch.Id];

                btch[0].RemainingContracts__c = totalDataSources - planDocsCreated;
                btch[0].TotalContracts__c = planDocsCreated;
                btch[0].EndTime__c = datetime.now();
                if(syncDate != null)
                {
                    btch[0].specifydate__c = Date.valueOf(syncDate);
                }
                btch[0].Datasource__c = datasource;
                btch[0].Status__c = 'Completed';
                try
                {
                    update btch;
                    
                }
                catch(DmlException e) 
                {   
                    
                    return 'While updating Batch   ';
                }  
      
            }
            catch(Exception e)
            {
                
                return ''+e;
            }
    
            if(check == 'true')
                return BATCHID;
            else
                return 'false';
        }
        catch(Exception e)
        {
            return e.getMessage();
        }   
    }

    public static Sales_Contract__c populateSalesContractLevels(Sales_Contract__c sc, Approvers__c approver, String userId)
    {
        User[] user = [Select Id,managerId from User us where us.Id=:userId];
        if(approver.Level1__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level1__c = user[0].managerId;
            sc.Level1_Due_Date__c = approver.Level1_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level2__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level2__c = user[0].managerId;
            sc.Level2_Due_Date__c = approver.Level2_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level3__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level3__c = user[0].managerId;
            sc.Level3_Due_Date__c = approver.Level3_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level4__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level4__c = user[0].managerId;
            sc.Level4_Due_Date__c = approver.Level4_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level5__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level5__c = user[0].managerId;
            sc.Level5_Due_Date__c = approver.Level5_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level6__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level6__c = user[0].managerId;
            sc.Level6_Due_Date__c = approver.Level6_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level7__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level7__c = user[0].managerId;
            sc.Level7_Due_Date__c = approver.Level7_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level8__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level8__c = user[0].managerId;
            sc.Level8_Due_Date__c = approver.Level8_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level9__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level9__c = user[0].managerId;
            sc.Level9_Due_Date__c = approver.Level9_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level10__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level10__c = user[0].managerId;
            sc.Level10_Due_Date__c = approver.Level10_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level11__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level11__c = user[0].managerId;
            sc.Level11_Due_Date__c = approver.Level11_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level12__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level12__c = user[0].managerId;
            sc.Level12_Due_Date__c = approver.Level12_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level13__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level13__c = user[0].managerId;
            sc.Level13_Due_Date__c = approver.Level13_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level14__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level14__c = user[0].managerId;
            sc.Level14_Due_Date__c = approver.Level14_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Level15__c != null && user.size() > 0 && user[0].managerId != null)
        {
            sc.Level15__c = user[0].managerId;
            sc.Level15_Due_Date__c = approver.Level15_Due_Date__c;
            if(testVar == '')
                user = [Select Id,managerId from User us where us.Id= :user[0].managerId];
        }
        if(approver.Final_Approver__c != null)
        {
            sc.Final_Approver__c = approver.Final_Approver__c;
            sc.Final_Approver_Date__c = approver.Final_Approver_Date__c;
        }
    
        return sc;
    }//end of public static populateSalesContractLevels()
    

WebService static String sendMailToUser(String userId, String subject, String textBody, String htmlBody)
{   
    System.LoggingLevel level = LoggingLevel.DEBUG;
    User[] u = [Select FirstName, Email from User us where us.Id = :userId];
    if(u.size() == 0)
    {
        return 'No User exists';
    }
    String firstName = u[0].FirstName;
    
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    // Strings to hold the email addresses to which you are sending the email.
    String[] toAddresses = new String[] {u[0].Email}; 
    String[] ccAddresses = new String[] {};
  

    // Assign the addresses for the To and CC lists to the mail object.
    mail.setToAddresses(toAddresses);
    mail.setCcAddresses(ccAddresses);

    // Specify the name used as the display name.
    mail.setSenderDisplayName('Salesforce OnDemand');

    // Specify the subject line for your email address.
    mail.setSubject(''+subject+'');

    // Set to True if you want to BCC yourself on the email.
    mail.setBccSender(false);
    
    // Optionally append the salesforce.com email signature to the email.
    // The email address of the user executing the Apex Code will be used.
    mail.setUseSignature(false);
    
    // Specify the text content of the email.
    mail.setPlainTextBody(''+textBody+'');

    mail.setHtmlBody('Dear <b>'+firstName+'</b>,<br/><br/>'+htmlBody+'');

    // Send the email you have created.
    Messaging.SendEmailResult[] ser = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    if(ser.size() > 0 && ser[0].getErrors().size() > 0)
        return 'success = '+ser[0].isSuccess()+'  = '+(ser[0].getErrors())[0].getMessage();
    else 
        return 'success '+ser[0].IsSuccess();
}//end of method sendMailToUser

	WebService static String updateStatus(String salesContractName)
	{  
	  
	   Sales_Contract__c[] sc = [SELECT Status__c, Name from Sales_Contract__c s where s.Name = :salesContractName];
	   if(sc.size() == 0)
	   {
	       return 'Sales Contract Id does not exist';
	   }
	   try{
	       if(sc[0]!= null)
	       {
	           sc[0].Status__c = 'Accepted';
	           sc[0].DateAccepted__c=System.now();
	           
	            if(testVar != '' && testVar.length() > 0)
	            {
	                sc[0].Level1__c = '005400000011epc';
	                sc[0].Level2__c = '005400000011epc';
	                sc[0].Level3__c = '005400000011epc';
	                sc[0].Level4__c = '005400000011epc';
	                sc[0].Level5__c = '005400000011epc';
	                sc[0].Level6__c = '005400000011epc';
	                sc[0].Level7__c = '005400000011epc';
	                sc[0].Level8__c = '005400000011epc';
	                sc[0].Level9__c = '005400000011epc';
	                sc[0].Level10__c = '005400000011epc';
	                sc[0].Level11__c = '005400000011epc';
	                sc[0].Level12__c = '005400000011epc';
	                sc[0].Level13__c = '005400000011epc';
	                sc[0].Level14__c = '005400000011epc';
	                sc[0].Level15__c = '005400000011epc';
	                sc[0].Final_Approver__c = '005400000011epc';
	                sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
	            }
	    
	            if(testVar == 'Published')
	            {
	                sc[0].Status__c = 'Published';
	            }
	            if(testVar == 'Plan Approved 1')
	                sc[0].Status__c = 'Plan Approved by Engineering Callidus';
	            if(testVar == 'Plan Rejected 1')
	                sc[0].Status__c = 'Plan Rejected by Engineering Callidus';
	    
	            if(testVar != '' && testVar.length() > 0)
	            {
	                sc[0].Level1__c = '005400000011eqL';
	                sc[0].Level2__c = '005400000011eqL';
	                sc[0].Level3__c = '005400000011eqL';
	                sc[0].Level4__c = '005400000011eqL';
	                sc[0].Level5__c = '005400000011eqL';
	                sc[0].Level6__c = '005400000011eqL';
	                sc[0].Level7__c = '005400000011eqL';
	                sc[0].Level8__c = '005400000011eqL';
	                sc[0].Level9__c = '005400000011eqL';
	                sc[0].Level10__c = '005400000011eqL';
	                sc[0].Level11__c = '005400000011eqL';
	                sc[0].Level12__c = '005400000011eqL';
	                sc[0].Level13__c = '005400000011eqL';
	                sc[0].Level14__c = '005400000011eqL';
	                sc[0].Level15__c = '005400000011eqL';
	                sc[0].Final_Approver__c = '005400000011eqL';
	                sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
	            }
	            if(testVar == 'Plan Approved 2')
	                sc[0].Status__c = 'Plan Approved by Jack Hill';
	            if(testVar == 'Plan Rejected 2')
	                sc[0].Status__c = 'Plan Rejected by Jack Hill';
	                
	           update sc;
	       }
	   }
	   catch(DmlException e){}
	   return 'success';
	}

	WebService static String updateTemplateStatus(String templateId)
	{  
	   Template__c[] tmp = [SELECT Status__c from Template__c t where t.Id = :templateId];
	   if(tmp.size() > 0)
	   {
	       tmp[0].Status__c = 'In Use';
	       try
	       {
	           update tmp;
	       }
	       catch(DmlException e)
	       {
	           return e.getMessage();
	       }
	    }
	    return 'success';
	}

	WebService static String defineEligibility(Attachment[] templateAttachment,String templateId, String requiredDate,String datasource,Template_Role__c[] tempTitles,List<Sales_Contract__c> planDocumentsList,TemplateDataMap__c[]  tempDataMap,String BATCHID)
	{
	    return '';
	}


    WebService static String defineEligibility2(String attachmentId,String templateId, String requiredDate,String datasource,Template_Role__c[] tempTitles,List<Sales_Contract__c> planDocumentsList,TemplateDataMap__c[]  tempDataMap, String BATCHID, String effectiveStartDate, String effectiveEndDate)
    {
        CallidusDataSource__c[] dsc=null;
        Sales_Contract__c[] contracts= null;
        String check = 'false';
        Integer totalDataSources = 0;
        Integer planDocsCreated = 0;
        String syncDate = '';
        Date dt = Date.today();
        Template__c[] templateName = [SELECT Id, Name  FROM Template__c t where t.Id= :templateId];
    
        //Get the Approvers assigned for this Template by Admin before generation of Plan Documents.
        Approvers__c[] approver = [select Admin__c, Template__c, Final_Approver__c, Final_Approver_Date__c, Level1__c, Level2__c, Level3__c, Level4__c, Level5__c, Level6__c, Level7__c, Level8__c, Level9__c, Level10__c, Level11__c, Level12__c, Level13__c, Level14__c, Level15__c, Level1_Due_Date__c, Level2_Due_Date__c, Level3_Due_Date__c, Level4_Due_Date__c, Level5_Due_Date__c, Level6_Due_Date__c, Level7_Due_Date__c, Level8_Due_Date__c, Level9_Due_Date__c, Level10_Due_Date__c, Level11_Due_Date__c, Level12_Due_Date__c, Level13_Due_Date__c, Level14_Due_Date__c, Level15_Due_Date__c from Approvers__c  where Template__c = :templateId and Admin__c = :UserInfo.getUserId() order by CreatedDate desc limit 1];
    
        URL__c[] url = [SELECT Id, Url_Value__c FROM URL__c];
    
        try
        {    
            for(Template_Role__c titles:tempTitles)
            {
                for(CallidusDataSource__c[] src : [SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,UserID__c,UserRoleId__c,UserRoleName__c,User_Title__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.User_Title__c=:titles.User_Title__c])
                {
                    contracts = new Sales_Contract__c[src.size()];
                    totalDataSources += src.size();
                    Integer i = 0;
                    for(CallidusDataSource__c sources : src)
                    {
                        syncDate = sources.SyncDate__c;
                        if(sources.PayeeID__c == null && dataSource == 'True Comp')
                        {
                            i++;
                            continue;
                        }
                          
                        check = 'true';  
                
                        contracts[i] = new Sales_Contract__c();
                        contracts[i].FirstName__c=sources.FirstName__c;
                        contracts[i].Generated_Date__c= dt;
                        contracts[i].LastName__c=sources.LastName__c;
                        contracts[i].Status__c= 'Draft';
                        contracts[i].UserID__c= sources.UserID__c;
                        contracts[i].User_ID__c= sources.UserID__c;
                        contracts[i].UserRoleId__c=sources.UserRoleId__c;
                        contracts[i].User_Title__c=sources.User_Title__c;
                        contracts[i].PayeeID__c=sources.PayeeID__c;
                        contracts[i].UserRoleName__c= sources.UserRoleName__c;
                        contracts[i].TemplateName__c= templateName[0].Name;
                        contracts[i].BatchID__c = BATCHID;
                        if(url.size() > 0)
                        {
                            contracts[i].Url__c=url[0].Url_Value__c;
                        }
                        if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                        {
                            contracts[i].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                        }
                        
                        if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                        {
                            contracts[i].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                        }
                
                        if(dt.month() > 9)
                            contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+sources.FirstName__c+' '+sources.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                        else
                            contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+sources.FirstName__c+' '+sources.LastName__c+' 0'+dt.month()+'/'+dt.day()+'/'+dt.year();
                
                        if(approver.size() > 0)
                        {
                            if(testVar != '' && testVar.length() > 0)
                            {
                                approver[0].Level1__c = '005400000011eqL';
                                approver[0].Level2__c = '005400000011eqL';
                                approver[0].Level3__c = '005400000011eqL';
                                approver[0].Level4__c = '005400000011eqL';
                                approver[0].Level5__c = '005400000011eqL';
                                approver[0].Level6__c = '005400000011eqL';
                                approver[0].Level7__c = '005400000011eqL';
                                approver[0].Level8__c = '005400000011eqL';
                                approver[0].Level9__c = '005400000011eqL';
                                approver[0].Level10__c = '005400000011eqL';
                                approver[0].Level11__c = '005400000011eqL';
                                approver[0].Level12__c = '005400000011eqL';
                                approver[0].Level13__c = '005400000011eqL';
                                approver[0].Level14__c = '005400000011eqL';
                                approver[0].Level15__c = '005400000011eqL';
                                approver[0].Final_Approver__c = '005400000011eqL';
                                approver[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                            }
                                                

                            contracts[i] = populateSalesContractLevels(contracts[i], approver[0], sources.UserID__c);
                        }    
                        if(requiredDate.length() > 7 && requiredDate.length() <= 10)
                        {
                            contracts[i].RequiredReturnDate__c = Date.valueOf(requiredDate);
                        }
                        
                        if(datasource!='True Comp')
                        {
                            contracts[i].Name1__c = sources.Name1__c;
                            contracts[i].Name2__c = sources.Name2__c;
                            contracts[i].Name3__c = sources.Name3__c;   
                            contracts[i].Name4__c = sources.Name4__c;
                            contracts[i].Name5__c = sources.Name5__c;
                            contracts[i].Name6__c = sources.Name6__c;     
                            contracts[i].Name7__c = sources.Name7__c;
                            contracts[i].Name8__c = sources.Name8__c;
                            contracts[i].Name9__c = sources.Name9__c;   
                            contracts[i].Name10__c = sources.Name10__c;
                            contracts[i].Name11__c = sources.Name11__c;
                            contracts[i].Name12__c = sources.Name12__c;     
                            contracts[i].Name13__c = sources.Name13__c;
                            contracts[i].Name14__c = sources.Name14__c;
                            contracts[i].Name15__c = sources.Name15__c;   
                            contracts[i].Name16__c = sources.Name16__c;
                            contracts[i].Name17__c = sources.Name17__c;
                            contracts[i].Name18__c = sources.Name18__c;     
                            contracts[i].Name19__c = sources.Name19__c;
                            contracts[i].Name20__c = sources.Name20__c;
                            contracts[i].Name21__c = sources.Name21__c;   
                            contracts[i].Name22__c = sources.Name22__c;
                            contracts[i].Name23__c = sources.Name23__c;
                            contracts[i].Name24__c = sources.Name24__c;     
                            contracts[i].Name25__c = sources.Name25__c;
                            contracts[i].Name26__c = sources.Name26__c;
                            contracts[i].Name27__c = sources.Name27__c;   
                            contracts[i].Name28__c = sources.Name28__c;
                            contracts[i].Name29__c = sources.Name29__c;
                            contracts[i].Name30__c = sources.Name30__c;     
                
                            contracts[i].Value1__c = sources.Value1__c;
                            contracts[i].Value2__c = sources.Value2__c;
                            contracts[i].Value3__c = sources.Value3__c;
                            contracts[i].Value4__c = sources.Value4__c;
                            contracts[i].Value5__c = sources.Value5__c;
                            contracts[i].Value6__c = sources.Value6__c;
                            contracts[i].Value7__c = sources.Value7__c;
                            contracts[i].Value8__c = sources.Value8__c;
                            contracts[i].Value9__c = sources.Value9__c;
                            contracts[i].Value10__c = sources.Value10__c;
                            contracts[i].Value11__c = sources.Value11__c;
                            contracts[i].Value12__c = sources.Value12__c;
                            contracts[i].Value13__c = sources.Value13__c;
                            contracts[i].Value14__c = sources.Value14__c;
                            contracts[i].Value15__c = sources.Value15__c;
                            contracts[i].Value16__c = sources.Value16__c;
                            contracts[i].Value17__c = sources.Value17__c;
                            contracts[i].Value18__c = sources.Value18__c;
                            contracts[i].Value19__c = sources.Value19__c;
                            contracts[i].Value20__c = sources.Value20__c;
                            contracts[i].Value21__c = sources.Value21__c;
                            contracts[i].Value22__c = sources.Value22__c;
                            contracts[i].Value23__c = sources.Value23__c;
                            contracts[i].Value24__c = sources.Value24__c;
                            contracts[i].Value25__c = sources.Value25__c;
                            contracts[i].Value26__c = sources.Value26__c;
                            contracts[i].Value27__c = sources.Value27__c;
                            contracts[i].Value28__c = sources.Value28__c;
                            contracts[i].Value29__c = sources.Value29__c;
                            contracts[i].Value30__c = sources.Value30__c;
                        }
                        else
                        {
                            if(tempDataMap.size() > 0)
                            {   
                                
                                contracts[i].Name1__c = tempDataMap[0].Name1__c;
                                contracts[i].Name2__c = tempDataMap[0].Name2__c;
                                contracts[i].Name3__c = tempDataMap[0].Name3__c;   
                                contracts[i].Name4__c = tempDataMap[0].Name4__c;
                                contracts[i].Name5__c = tempDataMap[0].Name5__c;
                                contracts[i].Name6__c = tempDataMap[0].Name6__c;     
                                contracts[i].Name7__c = tempDataMap[0].Name7__c;
                                contracts[i].Name8__c = tempDataMap[0].Name8__c;
                                contracts[i].Name9__c = tempDataMap[0].Name9__c;   
                                contracts[i].Name10__c = tempDataMap[0].Name10__c;
                                contracts[i].Name11__c = tempDataMap[0].Name11__c;
                                contracts[i].Name12__c = tempDataMap[0].Name12__c;     
                                contracts[i].Name13__c = tempDataMap[0].Name13__c;
                                contracts[i].Name14__c = tempDataMap[0].Name14__c;
                                contracts[i].Name15__c = tempDataMap[0].Name15__c;   
                                contracts[i].Name16__c = tempDataMap[0].Name16__c;
                                contracts[i].Name17__c = tempDataMap[0].Name17__c;
                                contracts[i].Name18__c = tempDataMap[0].Name18__c;     
                                contracts[i].Name19__c = tempDataMap[0].Name19__c;
                                contracts[i].Name20__c = tempDataMap[0].Name20__c;
                                contracts[i].Name21__c = tempDataMap[0].Name21__c;   
                                contracts[i].Name22__c = tempDataMap[0].Name22__c;
                                contracts[i].Name23__c = tempDataMap[0].Name23__c;
                                contracts[i].Name24__c = tempDataMap[0].Name24__c;     
                                contracts[i].Name25__c = tempDataMap[0].Name25__c;
                                contracts[i].Name26__c = tempDataMap[0].Name26__c;
                                contracts[i].Name27__c = tempDataMap[0].Name27__c;   
                                contracts[i].Name28__c = tempDataMap[0].Name28__c;
                                contracts[i].Name29__c = tempDataMap[0].Name29__c;
                                contracts[i].Name30__c = tempDataMap[0].Name30__c; 
                            }
                    
                        }
                        
                        contracts[i].AttachmentID__c = attachmentId;
                        planDocumentsList.add(contracts[i]);
                        i++;
                        planDocsCreated++;
                        if(planDocumentsList.size() == 200 || i == src.size())
                        {
                            try
                            {
                                insert planDocumentsList;
                            }
                            catch(DmlException d)
                            {   
                                return 'While inserting Contracts   '+d+'   ';
                            }
                            Integer j=0;
                            String ids = '';
                            planDocumentsList.clear();
                
                        }//end of if(planDocumentsList.size() == 199) 
                        
                    }//end of for(CallidusDataSource__c sources : src)
                
                }//end of for(CallidusDataSource__c[] sources:[SELECT Name,FirstName__c,LastName__c,PayeeID__c,SyncDate__c,UserID__c,UserRoleId__c,UserRoleName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserRoleId__c=:roles.Role_ID__c])
                    
            }//end of for(Template_Role__c roles:tempRoles)
                   
            Batch__c[] btch = [SELECT Status__c,TotalContracts__c,RemainingContracts__c, EndTime__c,Datasource__c from Batch__c b where  b.Id = :BATCHID];
        
            btch[0].RemainingContracts__c = totalDataSources - planDocsCreated;
            btch[0].TotalContracts__c = planDocsCreated;
            btch[0].EndTime__c = datetime.now();
            if(syncDate != null)
            {
                btch[0].specifydate__c = Date.valueOf(syncDate);
            }
            btch[0].Datasource__c=datasource;
            btch[0].Status__c = 'Completed';
            try
            {
                update btch;
                
            }
            catch(DmlException e) 
            {   
                
                return 'While updating Batch   ';
            }  
            catch(Exception e)
            {
                
                return ''+e;
            }
        
            if(check == 'true')
                return BATCHID;
            else
                return 'false';
        }
        catch(Exception e)
        {
            return e.getMessage();
        }   
       
    }//end of defineEligibility2

WebService static String generateForUsers(String templateId,String batchId, String requiredDate,String datasource)
{   
    return '';
}

WebService static String generateForUsers2(String templateId,String batchId, String requiredDate,String datasource, String attachmentId, String effectiveStartDate, String effectiveEndDate)
{    
    String s = 'success';
    String unSpecificUsers = '';
    Approvers__c[] approver = [select Admin__c, Template__c, Final_Approver__c, Final_Approver_Date__c,  Level1__c, Level2__c, Level3__c, Level4__c, Level5__c, Level6__c, Level7__c, Level8__c, Level9__c, Level10__c, Level11__c, Level12__c, Level13__c, Level14__c, Level15__c, Level1_Due_Date__c, Level2_Due_Date__c, Level3_Due_Date__c, Level4_Due_Date__c, Level5_Due_Date__c, Level6_Due_Date__c, Level7_Due_Date__c, Level8_Due_Date__c, Level9_Due_Date__c, Level10_Due_Date__c, Level11_Due_Date__c, Level12_Due_Date__c, Level13_Due_Date__c, Level14_Due_Date__c, Level15_Due_Date__c from Approvers__c  where Template__c = :templateId and Admin__c = :UserInfo.getUserId() order by CreatedDate desc limit 1];

    URL__c[] url = [SELECT Id, Url_Value__c FROM URL__c];

    //Get the AttachmentId of an Attachment associated with the Template.
    Attachment[] templateAttachment = [SELECT Id FROM Attachment a where a.Parent.Id = :templateId];
    if(templateAttachment.size() == 0)
        return 'null';
    
    //Start: Code to check whether all selected users belong to Roles or Titles associated with the Template.
    Template__c[] templateName = [SELECT Id, Name, EligibilityType__c FROM Template__c t where t.Id= :templateId];
    Map<String, String> trMap = new Map<String, String>();

    if(templateName.size() > 0 && templateName[0].EligibilityType__c == 'Title')
    {
        unSpecificUsers = 'TITLE';
        for(Template_Role__c[] tr : [select User_Title__c from Template_Role__c where Template__c = :templateId])
        {
            for(Template_Role__c t: tr)
            {
                trMap.put(t.User_Title__c, t.User_Title__c);
            }
            
        }
        for(BatchedUser__c[] batchedUsers: [SELECT User_Title__c FROM BatchedUser__c bu where bu.Batchid__c = :batchId])
        {
            for(BatchedUser__c b: batchedUsers)
            {
                if(trMap.get(b.User_Title__c) == null)
                {
                    unSpecificUsers += '@'+b.User_Title__c;
                }
            }
            
        }
        if(unSpecificUsers != 'TITLE')
            return unSpecificUsers;
    }   
    
    if(templateName.size() > 0 && templateName[0].EligibilityType__c == 'Role')
    {
        unSpecificUsers = 'ROLE';

        for(Template_Role__c[] tr : [select Role_ID__c from Template_Role__c where Template__c = :templateId])
        {
            for(Template_Role__c t: tr)
            {
                trMap.put(t.Role_ID__c, t.Role_ID__c);
            }
        }

        String bUser = '';
        
        for(BatchedUser__c[] batchedUsers : [SELECT UserRoleId__c FROM BatchedUser__c bu where bu.Batchid__c = :batchId])
        {
            for(BatchedUser__c b: batchedUsers)
            {
                if(trMap.get(b.UserRoleId__c) == null)
                {
                    UserRole[] ur = [select Name from UserRole where Id = :b.UserRoleId__c];
                    if(ur.size() > 0)
                        unSpecificUsers += '@'+ur[0].Name;
                }
            }
            
        }
        if(unSpecificUsers != 'ROLE')
            return unSpecificUsers;
    }   

    //End: Code to check whether all selected users belong to Roles or Titles associated with the Template.

    Batch__c[] batch= null;
    List<Sales_Contract__c> planDocsList = new List<Sales_Contract__c>();
    
    Integer batchednums=0;

    batch  = [SELECT Id, Name, BatchID__c, Status__c, StartTime__c, EndTime__c, TotalContracts__c, RemainingContracts__c, TemplateId__c FROM Batch__c bc where bc.Id = :batchId];
    if(batch.size() > 0)
    {
        batch[0].StartTime__c=datetime.now();
        batch[0].Status__c='InProgress';

        if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
        {
            batch[0].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
        }
        
        if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
        {
            batch[0].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
        }


        try
        {
            update batch;
        }
        catch(DmlException e)
        {
            
            return e.getMessage();
        } 
    }
    
    
    String str=null;
    Date dt = Date.today();

    TemplateDataMap__c[]  tempDataMap = [SELECT Id, Name, TemplateName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c,Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c FROM TemplateDataMap__c tmap where tmap.TemplateName__c=:templateName[0].Name];
    
    Sales_Contract__c[] contracts= null;
    String check = 'false';
    Integer totContracts = 0;
    Integer planDocsCreated = 0;
    String syncDate = null;
    for(BatchedUser__c[] batchedUsers: [SELECT Batchid__c, UserId__c, UserRoleId__c, TemplateId__c,User_Title__c FROM BatchedUser__c bu where bu.Batchid__c = :batchId])
    {
        for(BatchedUser__c users : batchedUsers)
        {
            for(CallidusDataSource__c[] cds : [SELECT Name,FirstName__c,LastName__c,UserID__c,PayeeID__c,SyncDate__c,UserRoleId__c,UserRoleName__c,User_Title__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserId__c=:users.UserId__c])
            {
                totContracts += cds.size();
                contracts = new Sales_Contract__c[cds.size()];
 
                Integer i=0;
 
                if(cds.size() == 0)
                {
                    continue;
                }
                if(cds.size()>0)
                {

                    for(CallidusDataSource__c dsc: cds)
                    {
                        if(dsc.PayeeID__c == null && dataSource == 'True Comp')
                            continue;            

                        check = 'true';
                        
                        syncDate = dsc.SyncDate__c;
                        
                        contracts[i] = new Sales_Contract__c();
            
                        contracts[i].FirstName__c=dsc.FirstName__c;
            
                        contracts[i].LastName__c =dsc.LastName__c;
                        contracts[i].UserRoleId__c = dsc.UserRoleId__c;
                        
                        contracts[i].UserID__c=dsc.UserID__c; 
                        contracts[i].User_ID__c= dsc.UserID__c;

                        contracts[i].PayeeID__c=dsc.PayeeID__c;
                        contracts[i].UserRoleName__c=dsc.UserRoleName__c;
                        contracts[i].User_Title__c=dsc.User_Title__c;
                        
                        contracts[i].Generated_Date__c= dt;
                        contracts[i].Status__c= 'Draft';
                        contracts[i].isWSCall__c = false;
                        contracts[i].BatchID__c = batchId;
                        contracts[i].TemplateName__c = templateName[0].Name;
                        if(url.size() > 0)
                        {
                            contracts[i].Url__c=url[0].Url_Value__c;
                        }

                        if(effectiveStartDate.length() > 7 && effectiveStartDate.length() <= 10)
                        {
                            contracts[i].Effective_Start_Date__c = Date.valueOf(effectiveStartDate);
                        }
                        
                        if(effectiveEndDate.length() > 7 && effectiveEndDate.length() <= 10)
                        {
                            contracts[i].Effective_End_Date__c = Date.valueOf(effectiveEndDate);
                        }
     
                        if(dt.month() > 9)
                            contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+dsc.FirstName__c+' '+dsc.LastName__c+' '+dt.month()+'/'+dt.day()+'/'+dt.year();
                        else
                            contracts[i].Plan_Document_Name__c = templateName[0].Name+' '+dsc.FirstName__c+' '+dsc.LastName__c+' 0'+dt.month()+'/'+dt.day()+'/'+dt.year();

                        if(approver.size() > 0)
                        {
                            if(testVar != '' && testVar.length() > 0)
                            {
                                approver[0].Level1__c = '005400000011eqL';
                                approver[0].Level2__c = '005400000011eqL';
                                approver[0].Level3__c = '005400000011eqL';
                                approver[0].Level4__c = '005400000011eqL';
                                approver[0].Level5__c = '005400000011eqL';
                                approver[0].Level6__c = '005400000011eqL';
                                approver[0].Level7__c = '005400000011eqL';
                                approver[0].Level8__c = '005400000011eqL';
                                approver[0].Level9__c = '005400000011eqL';
                                approver[0].Level10__c = '005400000011eqL';
                                approver[0].Level11__c = '005400000011eqL';
                                approver[0].Level12__c = '005400000011eqL';
                                approver[0].Level13__c = '005400000011eqL';
                                approver[0].Level14__c = '005400000011eqL';
                                approver[0].Level15__c = '005400000011eqL';
                                approver[0].Final_Approver__c = '005400000011eqL';
                                approver[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                            }
                                            
                            contracts[i] = populateSalesContractLevels(contracts[i], approver[0], dsc.UserID__c);
                        }    
                        if(requiredDate.length() > 7 && requiredDate.length() <= 10)
                        {
                            contracts[i].RequiredReturnDate__c = Date.valueOf(requiredDate);
                        }
            
                        if(datasource!='True Comp')
                        {
                            contracts[i].Name1__c = dsc.Name1__c;
                            contracts[i].Name2__c = dsc.Name2__c;
                            contracts[i].Name3__c = dsc.Name3__c;   
                            contracts[i].Name4__c = dsc.Name4__c;
                            contracts[i].Name5__c = dsc.Name5__c;
                            contracts[i].Name6__c = dsc.Name6__c;     
                            contracts[i].Name7__c = dsc.Name7__c;
                            contracts[i].Name8__c = dsc.Name8__c;
                            contracts[i].Name9__c = dsc.Name9__c;   
                            contracts[i].Name10__c = dsc.Name10__c;
                            contracts[i].Name11__c = dsc.Name11__c;
                            contracts[i].Name12__c = dsc.Name12__c;     
                            contracts[i].Name13__c = dsc.Name13__c;
                            contracts[i].Name14__c = dsc.Name14__c;
                            contracts[i].Name15__c = dsc.Name15__c;   
                            contracts[i].Name16__c = dsc.Name16__c;
                            contracts[i].Name17__c = dsc.Name17__c;
                            contracts[i].Name18__c = dsc.Name18__c;     
                            contracts[i].Name19__c = dsc.Name19__c;
                            contracts[i].Name20__c = dsc.Name20__c;
                            contracts[i].Name21__c = dsc.Name21__c;   
                            contracts[i].Name22__c = dsc.Name22__c;
                            contracts[i].Name23__c = dsc.Name23__c;
                            contracts[i].Name24__c = dsc.Name24__c;     
                            contracts[i].Name25__c = dsc.Name25__c;
                            contracts[i].Name26__c = dsc.Name26__c;
                            contracts[i].Name27__c = dsc.Name27__c;   
                            contracts[i].Name28__c = dsc.Name28__c;
                            contracts[i].Name29__c = dsc.Name29__c;
                            contracts[i].Name30__c = dsc.Name30__c;     
                
                            contracts[i].Value1__c = dsc.Value1__c;
                            contracts[i].Value2__c = dsc.Value2__c;
                            contracts[i].Value3__c = dsc.Value3__c;
                            contracts[i].Value4__c = dsc.Value4__c;
                            contracts[i].Value5__c = dsc.Value5__c;
                            contracts[i].Value6__c = dsc.Value6__c;
                            contracts[i].Value7__c = dsc.Value7__c;
                            contracts[i].Value8__c = dsc.Value8__c;
                            contracts[i].Value9__c = dsc.Value9__c;
                            contracts[i].Value10__c = dsc.Value10__c;
                            contracts[i].Value11__c = dsc.Value11__c;
                            contracts[i].Value12__c = dsc.Value12__c;
                            contracts[i].Value13__c = dsc.Value13__c;
                            contracts[i].Value14__c = dsc.Value14__c;
                            contracts[i].Value15__c = dsc.Value15__c;
                            contracts[i].Value16__c = dsc.Value16__c;
                            contracts[i].Value17__c = dsc.Value17__c;
                            contracts[i].Value18__c = dsc.Value18__c;
                            contracts[i].Value19__c = dsc.Value19__c;
                            contracts[i].Value20__c = dsc.Value20__c;
                            contracts[i].Value21__c = dsc.Value21__c;
                            contracts[i].Value22__c = dsc.Value22__c;
                            contracts[i].Value23__c = dsc.Value23__c;
                            contracts[i].Value24__c = dsc.Value24__c;
                            contracts[i].Value25__c = dsc.Value25__c;
                            contracts[i].Value26__c = dsc.Value26__c;
                            contracts[i].Value27__c = dsc.Value27__c;
                            contracts[i].Value28__c = dsc.Value28__c;
                            contracts[i].Value29__c = dsc.Value29__c;
                            contracts[i].Value30__c = dsc.Value30__c;
                  
                        }
                        else
                        {    
                            contracts[i].Name1__c = tempDataMap[0].Name1__c;
                            contracts[i].Name2__c = tempDataMap[0].Name2__c;
                            contracts[i].Name3__c = tempDataMap[0].Name3__c;   
                            contracts[i].Name4__c = tempDataMap[0].Name4__c;
                            contracts[i].Name5__c = tempDataMap[0].Name5__c;
                            contracts[i].Name6__c = tempDataMap[0].Name6__c;     
                            contracts[i].Name7__c = tempDataMap[0].Name7__c;
                            contracts[i].Name8__c = tempDataMap[0].Name8__c;
                            contracts[i].Name9__c = tempDataMap[0].Name9__c;   
                            contracts[i].Name10__c = tempDataMap[0].Name10__c;
                            contracts[i].Name11__c = tempDataMap[0].Name11__c;
                            contracts[i].Name12__c = tempDataMap[0].Name12__c;     
                            contracts[i].Name13__c = tempDataMap[0].Name13__c;
                            contracts[i].Name14__c = tempDataMap[0].Name14__c;
                            contracts[i].Name15__c = tempDataMap[0].Name15__c;   
                            contracts[i].Name16__c = tempDataMap[0].Name16__c;
                            contracts[i].Name17__c = tempDataMap[0].Name17__c;
                            contracts[i].Name18__c = tempDataMap[0].Name18__c;     
                            contracts[i].Name19__c = tempDataMap[0].Name19__c;
                            contracts[i].Name20__c = tempDataMap[0].Name20__c;
                            contracts[i].Name21__c = tempDataMap[0].Name21__c;   
                            contracts[i].Name22__c = tempDataMap[0].Name22__c;
                            contracts[i].Name23__c = tempDataMap[0].Name23__c;
                            contracts[i].Name24__c = tempDataMap[0].Name24__c;     
                            contracts[i].Name25__c = tempDataMap[0].Name25__c;
                            contracts[i].Name26__c = tempDataMap[0].Name26__c;
                            contracts[i].Name27__c = tempDataMap[0].Name27__c;   
                            contracts[i].Name28__c = tempDataMap[0].Name28__c;
                            contracts[i].Name29__c = tempDataMap[0].Name29__c;
                            contracts[i].Name30__c = tempDataMap[0].Name30__c; 
                        }      
                        contracts[i].AttachmentID__c = templateAttachment[0].Id;
                        planDocsList.add(contracts[i]);
                        i++;
                        planDocsCreated++;
                        if(planDocsList.size() == 200)
                        {
                            try
                            {
                                insert planDocsList;
                            }
                            catch(DmlException d)
                            {   
                                return s+' IN CONTRACTS    '+d;
                            }
                            planDocsList.clear();
                
                        }//end of if(planDocsList.size() == 200)
                    }//end of for(CallidusDataSource dsc : cds)
                }//end of if(cds.size() > 0)
            }//end of for(CallidusDataSource__c[] cds : [SELECT Name,FirstName__c,LastName__c,UserID__c,PayeeID__c,SyncDate__c,UserRoleId__c,UserRoleName__c, Name1__c, Name2__c, Name3__c, Name4__c, Name5__c, Name6__c, Name7__c, Name8__c, Name9__c, Name10__c, Name11__c, Name12__c, Name13__c, Name14__c, Name15__c, Name16__c, Name17__c, Name18__c, Name19__c, Name20__c, Name21__c, Name22__c, Name23__c, Name24__c, Name25__c, Name26__c, Name27__c, Name28__c, Name29__c, Name30__c, Value1__c, Value2__c, Value3__c, Value4__c, Value5__c, Value6__c, Value7__c, Value8__c, Value9__c, Value10__c, Value11__c, Value12__c, Value13__c, Value14__c, Value15__c, Value16__c, Value17__c, Value18__c, Value19__c, Value20__c, Value21__c, Value22__c, Value23__c, Value24__c, Value25__c, Value26__c, Value27__c, Value28__c, Value29__c, Value30__c FROM CallidusDataSource__c dsc where dsc.UserId__c=:users.UserId__c])
        }//end of for(BatchedUser__c users : batchedUsers)
            
            
    }/* outer For */
    
    if(planDocsList.size() > 0)
    {
        try
        {
            insert planDocsList;
        }
        catch(DmlException d)
        {   
            return s+' IN CONTRACTS    '+d;
        }
        planDocsList.clear();

    }//end of if(planDocsList.size() > 0)

    
    if(batch.size() > 0)
    {
        Batch__c[] btch = [SELECT  TemplateId__c,specifydate__c, Status__c, EndTime__c, TotalContracts__c, RemainingContracts__c,Datasource__c from Batch__c b where b.Id = :batch[0].Id];
        if(btch.size() > 0)
        {
            btch[0].EndTime__c = datetime.now();
            btch[0].Status__c = 'Completed';
            btch[0].TemplateId__c = templateId;
            if(syncDate != null)
            {
                btch[0].specifydate__c = Date.valueOf(syncDate);
            }
            btch[0].Datasource__c = datasource;
            
            btch[0].TotalContracts__c = planDocsCreated;
            
            btch[0].RemainingContracts__c = totContracts - btch[0].TotalContracts__c;
            try
            {
                update btch;
            }
            catch(DmlException e)
            {
            
            } 
        }
    }//end of if(batch.size() > 0)

    return check;//'success';

}

WebService static String updateBatch(String batchId, String BatchName, String templateId, String SpecifyInDate, String RequiredDate, String url, String customButtonId){
    Batch__c[]  batch = [SELECT Id, Name, BatchID__c, Status__c, StartTime__c,EndTime__c, TotalContracts__c, RemainingContracts__c, Template__c, TemplateId__c, Owner.Id, Owner.Email FROM Batch__c bc where bc.Id = :batchId];
    if(batch.size() == 0)
    {
     return 'Batch does not exist';
    }
    String str = '';
    if(batch.size() > 0)
    { 
        batch[0].Name = BatchName;
        batch[0].Template__c = templateId;
        if(SpecifyInDate.length() > 7 && SpecifyInDate.length() <= 10 )
        {
            batch[0].specifydate__c = Date.valueOf(SpecifyInDate);
        }
        if(RequiredDate.length() > 7 && RequiredDate.length() <= 10)
        {
            batch[0].RequiredReturnDate__c = Date.valueOf(RequiredDate);
        }
        
        try
        {
            update batch;
        }
        catch(DmlException e) 
        { 
            return e.getMessage()+'   673';
        }
        
        String subject = 'Plan Document generation has completed for the Batch '+BatchName+'.';
        String textBody = 'Plan Document generation has been Generated.';
        String htmlBody = 'Plan Document Generation Completed for the Batch '+BatchName+'.<br/><a href="'+url+''+templateId+'">Click here</a> to view the Template used to create the batch.<br/><a href="'+url+'servlet/servlet.Integration?scontrolCaching=1&lid='+customButtonId+'&eid='+templateId+'&ic=1&rSel=all&bcId='+batchId+'">Click here</a> to view the Batch created.  ';
        
        //Send mail to Admin with a link to the contract.
        try
        {
            str = sendMailToUser(batch[0].Owner.Id, subject, textBody, htmlBody);
        }
        catch(Exception e)
        {
            return e.getMessage()+'    712';
        }
    }//end of if(batch.size() > 0)
         
    Sales_Contract__c[] sc = [select Id, Name, BatchName__c, Status__c, BatchID__c from Sales_Contract__c s where s.BatchID__c = :batchId];
    if(sc.size() > 0)
    {
        for(Integer p=0; p<sc.size(); p++)
        {
            sc[p].BatchName__c = BatchName;

            if(testVar != '' && testVar.length() > 0)
            {
                sc[0].Level1__c = '005400000011epc';
                sc[0].Level2__c = '005400000011epc';
                sc[0].Level3__c = '005400000011epc';
                sc[0].Level4__c = '005400000011epc';
                sc[0].Level5__c = '005400000011epc';
                sc[0].Level6__c = '005400000011epc';
                sc[0].Level7__c = '005400000011epc';
                sc[0].Level8__c = '005400000011epc';
                sc[0].Level9__c = '005400000011epc';
                sc[0].Level10__c = '005400000011epc';
                sc[0].Level11__c = '005400000011epc';
                sc[0].Level12__c = '005400000011epc';
                sc[0].Level13__c = '005400000011epc';
                sc[0].Level14__c = '005400000011epc';
                sc[0].Level15__c = '005400000011epc';
                sc[0].Final_Approver__c = '005400000011epc';
                sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
            }
    
            if(testVar == 'Published')
            {
                sc[0].Status__c = 'Published';
            }
            if(testVar == 'Plan Approved 1')
                sc[0].Status__c = 'Plan Approved by Engineering Callidus';
            if(testVar == 'Plan Rejected 1')
                sc[0].Status__c = 'Plan Rejected by Engineering Callidus';
    
            if(testVar != '' && testVar.length() > 0)
            {
                sc[0].Level1__c = '005400000011eqL';
                sc[0].Level2__c = '005400000011eqL';
                sc[0].Level3__c = '005400000011eqL';
                sc[0].Level4__c = '005400000011eqL';
                sc[0].Level5__c = '005400000011eqL';
                sc[0].Level6__c = '005400000011eqL';
                sc[0].Level7__c = '005400000011eqL';
                sc[0].Level8__c = '005400000011eqL';
                sc[0].Level9__c = '005400000011eqL';
                sc[0].Level10__c = '005400000011eqL';
                sc[0].Level11__c = '005400000011eqL';
                sc[0].Level12__c = '005400000011eqL';
                sc[0].Level13__c = '005400000011eqL';
                sc[0].Level14__c = '005400000011eqL';
                sc[0].Level15__c = '005400000011eqL';
                sc[0].Final_Approver__c = '005400000011eqL';
                sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
            }
            if(testVar == 'Plan Approved 2')
                sc[0].Status__c = 'Plan Approved by Jack Hill';
            if(testVar == 'Plan Rejected 2')
                sc[0].Status__c = 'Plan Rejected by Jack Hill';
        }
        
        try
        {
           update sc; 
        }
        catch(Exception e)
        {
            return e.getMessage()+'   While Updating BatchName for Plan Documents in updatBatch';
        }
    }
  return 'success '+testVar+'   email msg = '+str;
}

WebService static String updatePlanDocStatus(String[] salesContractId, String batchId, String url, String requiredReturnDate)
{
    return 'success';
}

WebService static String updatePlanDocStatus2(String[] salesContractId, String batchId, String url, String requiredReturnDate, String templateId)
{
    Approvers__c[] approver = [select Id, Admin__c, Template__c from Approvers__c  where Template__c = :templateId and Admin__c = :UserInfo.getUserId() order by CreatedDate desc limit 1];
    if(approver.size() > 0)
    {
       try
       {
           for(Integer k=0; k<salesContractId.size(); k++)
           {
               Sales_Contract__c[] sc = [SELECT Id, OwnerId, FirstName__c, LastName__c, Level1__c, Level1_Due_Date__c, Status__c, Name, UserID__c from Sales_Contract__c s where s.Id = :salesContractId[k]];
               if(sc[0].Level1__c != null)
               {
                   if(sc.size() == 0)
                   {
                       
                       return 'Sales Contract does not exist';
                   }

                   sc[0].Status__c = 'Distributed';
                
                   Batch__c[] b = [Select Status__c from Batch__c b where b.Id = :batchId];
                   if(b.size() > 0)
                   {
                       b[0].Status__c = 'Distributed';
                       try
                       {
                            if(testVar != '' && testVar.length() > 0)
                            {
                                sc[0].Level1__c = '005400000011epc';
                                sc[0].Level2__c = '005400000011epc';
                                sc[0].Level3__c = '005400000011epc';
                                sc[0].Level4__c = '005400000011epc';
                                sc[0].Level5__c = '005400000011epc';
                                sc[0].Level6__c = '005400000011epc';
                                sc[0].Level7__c = '005400000011epc';
                                sc[0].Level8__c = '005400000011epc';
                                sc[0].Level9__c = '005400000011epc';
                                sc[0].Level10__c = '005400000011epc';
                                sc[0].Level11__c = '005400000011epc';
                                sc[0].Level12__c = '005400000011epc';
                                sc[0].Level13__c = '005400000011epc';
                                sc[0].Level14__c = '005400000011epc';
                                sc[0].Level15__c = '005400000011epc';
                                sc[0].Final_Approver__c = '005400000011epc';
                                sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                            }
                    
                            if(testVar == 'Published')
                            {
                                sc[0].Status__c = 'Published';
                            }
                            if(testVar == 'Plan Approved 1')
                                sc[0].Status__c = 'Plan Approved by Engineering Callidus';
                            if(testVar == 'Plan Rejected 1')
                                sc[0].Status__c = 'Plan Rejected by Engineering Callidus';
                    
                            if(testVar != '' && testVar.length() > 0)
                            {
                                sc[0].Level1__c = '005400000011eqL';
                                sc[0].Level2__c = '005400000011eqL';
                                sc[0].Level3__c = '005400000011eqL';
                                sc[0].Level4__c = '005400000011eqL';
                                sc[0].Level5__c = '005400000011eqL';
                                sc[0].Level6__c = '005400000011eqL';
                                sc[0].Level7__c = '005400000011eqL';
                                sc[0].Level8__c = '005400000011eqL';
                                sc[0].Level9__c = '005400000011eqL';
                                sc[0].Level10__c = '005400000011eqL';
                                sc[0].Level11__c = '005400000011eqL';
                                sc[0].Level12__c = '005400000011eqL';
                                sc[0].Level13__c = '005400000011eqL';
                                sc[0].Level14__c = '005400000011eqL';
                                sc[0].Level15__c = '005400000011eqL';
                                sc[0].Final_Approver__c = '005400000011eqL';
                                sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                            }
                            if(testVar == 'Plan Approved 2')
                                sc[0].Status__c = 'Plan Approved by Jack Hill';
                            if(testVar == 'Plan Rejected 2')
                                sc[0].Status__c = 'Plan Rejected by Jack Hill';
                                
                           update sc;
                           update b;
                       }
                       catch(DmlException e)
                       {  
                          return 'While Updating SalesContract and Batch  '+e;
                       }
                       Approval.ProcessSubmitRequest request =new Approval.ProcessSubmitRequest();
                       request.setObjectId(sc[0].Id);
                       Approval.ProcessResult result = Approval.process(request);
            
                   }
                
                   Task t = new Task();
                   t.OwnerId = sc[0].Level1__c;
                   t.WhatId = sc[0].Id;
                   t.Subject = 'Plan Document Distributed';
                   t.Description = 'Plan Document Distributed.';
                   t.Status = 'NotStarted';
                   t.Type = 'Email';
                   t.ActivityDate = sc[0].Level1_Due_Date__c;//Date.valueof(requiredReturnDate);
                   String remDateTime = sc[0].Level1_Due_Date__c+' 08:00:00';
                   t.ReminderDateTime = Datetime.valueof(remDateTime) - 3;
                   t.IsReminderSet = true;
                   t.Priority = 'Normal';
                
                   try
                   {
                     insert t;
                   }
                   catch(DmlException d)
                   { 
                     
                     return ' '+d;
                   }
                   Sales_Contract__History history = new Sales_Contract__History(ParentId = salesContractId[k]);
                   
                    //Give access to the user to access his Plan Document
                   String shareUser = shareRecordToUser(sc[0].Id, sc[0].Level1__c);
    
                }
            }
        }
        catch(Exception e)
        {
            
            return 'List has no rows  '+e.getMessage();
        }
    }
    else
    {
       try
       {
           for(Integer k=0; k<salesContractId.size(); k++)
           {
               Sales_Contract__c[] sc = [SELECT Id, OwnerId, Status__c, Name,UserID__c from Sales_Contract__c s where s.Id = :salesContractId[k]];
            
               if(sc.size() == 0)
               {
                   return 'Sales Contract does not exist';
               }

               sc[0].Status__c = 'Published';

               Batch__c[] b = [Select Status__c from Batch__c b where b.Id = :batchId];
               if(b.size() > 0)
               {
                   b[0].Status__c = 'Distributed';
                   try
                   {

                        if(testVar != '' && testVar.length() > 0)
                        {
                            sc[0].Level1__c = '005400000011epc';
                            sc[0].Level2__c = '005400000011epc';
                            sc[0].Level3__c = '005400000011epc';
                            sc[0].Level4__c = '005400000011epc';
                            sc[0].Level5__c = '005400000011epc';
                            sc[0].Level6__c = '005400000011epc';
                            sc[0].Level7__c = '005400000011epc';
                            sc[0].Level8__c = '005400000011epc';
                            sc[0].Level9__c = '005400000011epc';
                            sc[0].Level10__c = '005400000011epc';
                            sc[0].Level11__c = '005400000011epc';
                            sc[0].Level12__c = '005400000011epc';
                            sc[0].Level13__c = '005400000011epc';
                            sc[0].Level14__c = '005400000011epc';
                            sc[0].Level15__c = '005400000011epc';
                            sc[0].Final_Approver__c = '005400000011epc';
                            sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                        }
                
                        if(testVar == 'Published')
                        {
                            sc[0].Status__c = 'Published';
                        }
                        if(testVar == 'Plan Approved 1')
                            sc[0].Status__c = 'Plan Approved by Engineering Callidus';
                        if(testVar == 'Plan Rejected 1')
                            sc[0].Status__c = 'Plan Rejected by Engineering Callidus';
                
                        if(testVar != '' && testVar.length() > 0)
                        {
                            sc[0].Level1__c = '005400000011eqL';
                            sc[0].Level2__c = '005400000011eqL';
                            sc[0].Level3__c = '005400000011eqL';
                            sc[0].Level4__c = '005400000011eqL';
                            sc[0].Level5__c = '005400000011eqL';
                            sc[0].Level6__c = '005400000011eqL';
                            sc[0].Level7__c = '005400000011eqL';
                            sc[0].Level8__c = '005400000011eqL';
                            sc[0].Level9__c = '005400000011eqL';
                            sc[0].Level10__c = '005400000011eqL';
                            sc[0].Level11__c = '005400000011eqL';
                            sc[0].Level12__c = '005400000011eqL';
                            sc[0].Level13__c = '005400000011eqL';
                            sc[0].Level14__c = '005400000011eqL';
                            sc[0].Level15__c = '005400000011eqL';
                            sc[0].Final_Approver__c = '005400000011eqL';
                            sc[0].Final_Approver_Date__c = Date.valueof('2008-06-26');
                        }
                        if(testVar == 'Plan Approved 2')
                            sc[0].Status__c = 'Plan Approved by Jack Hill';
                        if(testVar == 'Plan Rejected 2')
                            sc[0].Status__c = 'Plan Rejected by Jack Hill';
                               
                       update sc;
                       update b;
                   }
                   catch(DmlException e)
                   {  
                      return 'While Updating SalesContract and Batch  '+e;
                   }
               }
            }
        }
        catch(Exception e)
        {
            
            return 'List has no rows  '+e.getMessage();
        }
        
    }
    return 'success';
}


WebService static String getCurrentDateTime(String time1){
    Datetime dt = Datetime.now();
    dt.format('MM/dd/yyyy hh:mm:ss a');
    return ' '+dt.format('MM/dd/yyyy hh:mm:ss a');
}

WebService static String shareRecordToUser(String contractId, String userId){

      Sales_Contract__Share scShare  = new Sales_Contract__Share();
      
      scShare.ParentId = contractId;
      
      // Set the ID of user or group being granted access.
      scShare.UserOrGroupId = userId;
      
      
      // Set the access level.
      scShare.AccessLevel = 'read';
      
      // Set rowCause to 'manual' for manual sharing.
      // This line can be omitted as 'manual' is the default value for sharing objects.
      scShare.RowCause = Schema.Sales_Contract__Share.RowCause.Manual;
      
      // Insert the sharing record and capture the save result. 
      // The false parameter allows for partial processing if multiple records passed 
      // into the operation.
      Database.SaveResult sr = Database.insert(scShare,false);

      // Process the save results.
         if(!sr.isSuccess()){
            // Get first save result error.
            Database.Error err = sr.getErrors()[0];
            
         // Check if the error is related to trival access level.
         // Access levels equal or more permissive than the object's default 
         // access level are not allowed. 
         // These sharing records are not required and thus an insert exception is acceptable. 
            if(err.getStatusCode() == StatusCode.FIELD_INTEGRITY_EXCEPTION  &&  
                                                  err.getMessage().contains('AccessLevel')){
               // Indicates success.
               return 'Success in IF'+err;
            }
            else{
               // Indicates failure.
               return 'Failure';
            }
         }
         else{
            // Indicates success.
            return 'Success in Else';   
         }
         return 'success';
}

WebService static String[] getTemplateAttachments(String templateId)
{
    Attachment[] a = [select Id, Name, Body from Attachment a where a.Parent.Id = :templateId];
    String[] attachmentsList = new List<String>();
    if(a.size() > 0)
    {
        String body = '';
        for(Integer i=0;i<a.size();i++)
        {
            body = a[i].Body.toString();
            Integer indexOfBody = body.indexOf('<body', 0);
            if(indexOfBody == -1)
                indexOfBody = body.indexOf('<Body', 0);

            if(indexOfBody == -1)
                indexOfBody = body.indexOf('<BODY', 0);
            
            String extractedBody = '';
            if(indexOfBody != -1)
            {
                extractedBody = body.substring(indexOfBody);
            
                Integer indexOfLFB = extractedBody.indexOf('{', 0);
                Integer indexOfRFB = extractedBody.indexOf('}', 0);
                
                if(indexOfLFB != -1 && indexOfRFB != -1)
                {
                    attachmentsList.add(a[i].Id);
                    attachmentsList.add(a[i].Name);
                }
            }
        }//end of for
    }//end of if(a.size())
    
    return attachmentsList;
}//end of getTemplateAttachments()

static testMethod void testCase() {
    getTemplateAttachments('a0D40000001mHXT');
    
    testVar = 'Published';
    updateStatus('020300');
    testVar = 'Plan Approved 1';
    updateStatus('020300');
    testVar = 'Plan Rejected 1';
    updateStatus('020300');
    testVar = 'Plan Rejected 2';
    updateStatus('020300');
    testVar = 'Plan Approved 2';
    updateStatus('020300');

    generateForUsers2('a0D40000002PMfx','a0J40000000QsgBEAS','2008-06-25','Local', '', '2008-06-25', '2008-06-25');
    generateForUsers2('a0D40000001mHXT','a0J40000000OSt8EAG','2008-06-25','True Comp', '', '2008-06-25', '2008-06-25');

    generateContract('a0D40000001mHXT','2008-06-26','Local');

    generateContract2('a0D400000020eAQ','2008-06-26','Local', '', '2008-06-25', '2008-06-25');
    generateContract2('a0D400000020eAQ','2008-06-26','True Comp', '', '2008-06-25', '2008-06-25');
    generateContract2('a0D40000001mHXT','2008-06-26','Local', '', '2008-06-25', '2008-06-25');

    sendMailToUser('005400000011eqL','test','test','test');
    
    updateTemplateStatus('a0D400000020eAQ');
    GenerateUtil.generateForUsers('a0D40000001mHXT','a0J40000000OSt8EAG','2008-06-25','Local');

    updateBatch('a0J40000000OSt8EAG','Gforce2 06/26/2008 05:24:09 AM','a0D40000001mHXT','2008-06-17','2008-06-25','https://www.yahoo.com','test');
    updatePlanDocStatus(new String[]{'a0E40000000knbh'}, 'a0J40000000OSt8EAG','https://www.yahoo.com','2008-06-25');

    updatePlanDocStatus2(new String[]{'a0E40000000knbh'}, 'a0J40000000OSt8EAG','https://www.yahoo.com','2008-06-25', 'a0D400000020eAQ');
    shareRecordToUser('a0E40000000knbh','005400000011eqL');

    GenerateUtil.getCurrentDateTime('01:49:44 AM');
}



}